import {objectCompare}  from '../../../assets/js/objectCompare.js'
import {selectAttr} from '../../../assets/js/selectAttr.js'
export default {
  data() {
    return {
      /**
       * pageData 是 页面的数据  moudelData 模块数据 roleData role数据
       */
      //请求后台路径
      SRC:'',
      pageData : '',
      moudelData: [],
      roleData: [],
      mergeData:'',
      filterData: [],
      // 添加角色
      moudleShow: false,
      // 修改角色
      revampShow: false,
      // 修改过滤
      filterShow: false,
      roleShow: true,
      // 存储roleid
      roleId: 0,
      // 角色选择数组
      checkedKeys : [],
      /*roleTable 的宽*/
      roleTable:'100%',
      // deleteBtn 显示
      deleteBtn: false,
      // 表格数据
      tableData: [],
      // tree 数据
      data2: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存放表格每一行选择的数据
      multipleSelection: [],
      ruleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }, 
      revampForm: {
        id : 0,
        name: '',
        description: ''
      },
      revampRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }, 
      filterForm: {
        filterName: '',
        filterId: 0,
        filterDepartment: ''
      },
      filters: {
        filterName: [
          { required: true, message: '请输入模块名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        filterId: [
          { required: true, message: 'ID不能为空'},
          { type: 'number', message: 'ID必须为数字值'}
        ]
      },  
      controlForm: {
        roleId: 0,
        functionId: 0,
        filter1: '',
        filterVal1: '',
        filter2: '',
        filterVal2: '',
        filter3: '',
        filterVal3: ''
      }    
    }
  },
  methods: {
    // 通用 成功 与 失败
    successFun(data) {
      this.$message({
        message: data,
        type: 'success'
      });
    },
    errorFun(data) {
      this.$message.error(data);
    },
    // 模块展
    moudleShowFun() {
      this.ruleForm.name ='';
      this.ruleForm.description = '';
      this.moudleShow = true;
    },
    //编辑用户
    roleEdit(index, row) {
      this.revampForm = row;
      this.revampShow = true;
    },
    // 请求数据 role_function
    getRoleFunction(i) {
      var that = this;
      var p = new Promise(function(resolve,reject){
        that.$http.post(that.SRC+"role_function/list.do",{id:i},{emulateJSON:true}).then(
          function(res){
            if(res.body["code"] == 0){
              resolve(res.body['msg'])
            }else{
              that.errorFun("获取列表失败，"+res.body['msg']+"！");
            }
          }
        )
      })
      p.then(function(value){
        that.checkedKeys = [];
        // filter1:1,filterVal1:1,filter2:1,filterVal2:1,filter3:1,filterVal3:1
        for(var i = 0; i<value.length; i++){          
          that.checkedKeys.push(value[i]['functionId'])
        }
        that.pooledData(value);
        that.roleData = value;
        that.setCheckedKeys(that.checkedKeys);
        that.roleShow = false;
      })
    },
    // 编辑权限  
    handleEdit(index, row) {
      var that = this;
      this.roleId = row.id;
      this.getRoleFunction(row.id);
    },
    // 删除用户
    handleDelete(index, row) {
      this.$http.post(this.SRC+"role/delete.do",{id:row.id},{emulateJSON:true}).then(
        function(res) {
          if(res.body["code"] === 0 ){
            this.successFun('删除成功！')
            this.getRoleData();
          }else{
            this.errorFun('删除失败！')
          }
        }
      )
    },
    // 全部删除
    handleDeleteAll() {
      this.tableData=[];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if(val.length === this.tableData.length  &&  val.length>0){
        this.deleteBtn = true;
      }else{
        this.deleteBtn = false;
      }
    },
    // 默认选择目录
    setCheckedKeys(arr) {
      this.$refs.tree.setCheckedKeys(arr);
    },
    // 获取目录的functionId
    getCheckedKeys() {
      return this.$refs.tree.getCheckedKeys()
    },
    // 过滤
    filter(store, data , index){
      this.controlForm.roleId = this.roleId;
      this.controlForm.functionId = data.id;
      this.controlForm = data;
      this.filterShow = true;
    },
    // 渲染
    renderContent(h, { node, data, store }) {
      if(data["modelId"] === undefined){
        return (
        <span>
          <span>
            <span class="el-tag">{node.label}</span>
          </span>
          <span class = 'el-tag el-tag--primary' style="margin-left: 10px;">模块标识：{data.id}</span>
          <span class = 'el-tag el-tag--primary' style="margin-left: 10px;">模块描述：{data.description}</span>
        </span>);
      }else{
        return (
        <span>
          <span>
            <span class="el-tag el-tag--gray">{node.label}</span>
          </span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">页面标识：{data.id}</span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">页面SRC：{data.src}</span>
          <span class="el-tag el-tag--success" style="margin-left: 10px;">页面描述：{data.description}</span>
          <span style="float: right; margin-right: 20px">
            <el-button size="mini" type="info" on-click={ () =>
              this.filter(store, data , 0) }>{data.filter1}：{data.filterVal1}
            </el-button>
            <el-button size="mini" type="info" on-click={ () =>
              this.filter(store, data , 1) }>{data.filter2}：{data.filterVal2}
            </el-button>
            <el-button size="mini" type="info" on-click={ () =>
              this.filter(store, data , 2) }>{data.filter3}：{data.filterVal3}
            </el-button>
          </span>
        </span>);
      }
    },
    /*设置初始值*/
    _init(){
      window.addEventListener('resize', function() {
        /*修改表格的宽度*/
            this.roleTable = document.body.clientWidth-220+"px";
        }.bind(this))
    },
    // 添加角色提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var obj = {
            name : this.ruleForm.name,
            description : this.ruleForm.description
          }
          this.$http.post(this.SRC+"role/add.do",obj,{emulateJSON:true}).then(
            function(res){
              if(res.body["code"] === 0){
                this.successFun('添加成功！');
                this.getRoleData();
              }else{
                this.error("添加失败，"+res.body['msg']+"！");
              }
            }
          )
          this.tableData = objectCompare(this.tableData,"id")// 排序
        } else {
          return false;
        }
      });
    },
    // 添加角色重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }, 
    // 修改角色
    submitRevamp(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post(this.SRC+'role/modify.do',this.revampForm,{emulateJSON:true}).then(
            function(res){
              if(res.body["code"] === 0){
                this.successFun('修改成功！');
                this.getRoleData();
              }else{
                this.error("修改失败，"+res.body['msg']+"！");
              }
            }
          )
        } else {
          return false;
        }
      });
    },
    // 修改角色重置
    resetRevamp(formName) {
      this.$refs[formName].resetFields();
    }, 
    // 角色功能tree提交
    roleAddForm() {
        var d = this.getCheckedKeys();
        // this.roleData]
        var arr = [];
        for(var i = 0; i<d.length; i++){
          var obj = {};
          obj["functionId"] = d[i]
          arr.push(obj)
        }
        this.roleData = arr;
        var  o = {"roleId":this.roleId,"functions":this.roleData};
        this.$http.post(this.SRC+"role_function/modify.do",JSON.stringify(o)).then(
          function(res){
            if(res.body["code"] === 0){
              this.successFun('提交成功！');
              this.getRoleData();
            }else{
              this.error("提交失败，"+res.body['msg']+"！");
            }
          }
        )
    },
    // 角色功能tree重置
    roleReset() {
        this.setCheckedKeys([]);
    }, 
    // 过滤提交
    controlSub(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let c = this.controlForm;
          var obj = {
            roleId : this.roleId,
            functionId : c.functionId,
            filter1 : c.filter1,
            filterVal1 : c.filterVal1,
            filter2: c.filter2,
            filterVal2 : c.filterVal2,
            filter3 : c.filter3,
            filterVal3 : c.filterVal3
          }
          this.$http.post(this.SRC+"role_function/modifyfilter.do",obj,{emulateJSON:true}).then(function(res){
            if(res.body["code"] === 0){
              this.successFun('提交成功！');
              this.getRoleFunction(this.roleId);
            }else{
              this.errorFun("提交失败，"+res.body['msg']+"！");
            }
          })
        } else {
          return false;
        }
      });
    },
    // 过滤重置
    controlReset(formName) {
      this.$refs[formName].resetFields();
    }, 
    /**
     * 获取角色数据 
     */
    getRoleData() {
      this.$http.post(this.SRC+'role/list.do').then(
        function(res){
          if(res.body["code"] === 0){
            this.tableData = res.body["msg"];
          }else{
            this.errorFun(res.body['msg']);
          }
        }
      )
    },
    /**
     * 数据合并
     * http://10.236.44.220:8080/function/list.do
     * http://10.236.44.220:8080/model/list.do
     * http://10.236.44.220:8080/role_function/list.do
     */
    pooledData(data){
      var that = this;
      var pooled = [];
      function post(url){
        return new Promise(
          function(resolve,reject){
            that.$http.post(that.SRC+url).then(
              function(res){
                if(res.body['code'] === 0){
                  resolve(res.body['msg']);
                }else{
                  reject(false);
                }
              }
            )
          }
        )
      }
      var urlData = ["function/list.do","/model/list.do"]
      function renderAll() {
        return Promise.all([post(urlData[0]), post(urlData[1])]);
      }
      renderAll().then(function(value) {
        // value0 是 页面的数据  value1 模块数据
        that.pageData = value[0];
        for(var z = 0; z<value[0].length; z++){
          for(var y = 1; y<4; y++){
            var f = 'filter'+y;
            var fv = 'filterVal'+ y;
            if(value[0][z][f] === undefined){
              value[0][z][f] = "过滤名"+y;
              value[0][z][fv] = "过滤值"+y;
            }
          }
          for(var x = 0; x<data.length; x++){
            if(value[0][z]['id'] === data[x]['functionId']){
              for(var w = 1; w<4; w++){
                var key = 'filter'+w;
                var v = 'filterVal'+ w;
                if(data[x][key] !== undefined){
                  value[0][z][key] = data[x][key];
                  value[0][z][v] = data[x][v]
                }
              }
            }
          }
        }
        for(var i = 0; i<value[1].length; i++){
          value[1][i].children = [];
          for(var j = 0; j<value[0].length; j++){
            if(value[1][i]['id'] == value[0][j]['modelId']){
              value[1][i].children.push(value[0][j]);
              value[0][j]['functionId'] = value[0][j]['id'];
            }
          }
        }
        that.moudelData = value[1];
      })
    }
  },
  mounted() {
    this.SRC = this.$store.getters.src;
    this._init();
    this.getRoleData();
    this.data2 = objectCompare(this.data2,"id");
  }
}